package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaOrganization;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.vo.OaOrganizationVo;
import com.dkm.orproject.dkmoa.service.OaOrganizationService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.IdToobtainUtils;
import com.dkm.orproject.utils.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  @ClassName : OaOrganization  //类名
 *  @Description : 部门  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-08-05 10:41  //时间
 */
@RestController
@RequestMapping("OaOrganizationAction")
public class OaOrganizationAction {
    /**
     *   声明logger
     */
   private final static Logger logger = LoggerFactory.getLogger(OaOrganizationService.class);
    @Resource
    OaOrganizationService  organizationService;
    @Resource
    IdToobtainUtils utils;
    /**
     * 工具类
     */
    @Resource
    Tools tools;
    /**
     * 日志
     */
    OaLog log;
    /**
     * 登陆人
     */
    OaPersonnel person;
    /**
     * 回调map
     */
    Map<String,Object> map;
    /**
     * 行数
     */
    int row;

    /**
     * 查询岗位(下拉框)
     * @param request 请求
     * @return id 和部门
     */
    @GetMapping("/organizationFindAll")
    @UserLoginToken
    public Map<String, Object> findAll( HttpServletRequest request){
       rowMap(request);
        try {
            List<OaOrganization> all = organizationService.findByAll();
            return Tools.maps(all, null);
        } catch (Exception e) {
           addErrorLog(request,"查询岗位",e);
        }
        return  null;
    }

    /**
     * 根据部门ID查询岗位
     * @param request 请求
     * @return id 和部门
     */
    @GetMapping("/organizationFind/{departmentId}")
    @UserLoginToken
    public Map<String, Object> findById(@PathVariable("departmentId")Long departmentId, HttpServletRequest request){
        rowMap(request);
        try {
            List<OaOrganization> all = organizationService.findById(departmentId);
            return Tools.maps(all, null);
        } catch (Exception e) {
            addErrorLog(request,"查询部门",e);
        }
        return  null;
    }
    /**
     * 增加或者更新岗位
     * @param organization 岗位信息
     * @return 增加的数量
     */
    @PostMapping("addOrUpdateOrganization")
    @UserLoginToken
    public Map<String, Object> addOrUpdateCompany (OaOrganization organization, HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(organization)){
            tools.rowMap(map,0,null);
        }
        try {
            if (organization.getPkPostId()!=null &&organization.getPkPostId()>0){
                row= organizationService.update(organization,person.getPersonnelName());
                log.setLogTitle("岗位更新模块");
            }else {
                organization.setIsRevision("1");
                //公司id 随机生成
                organization.setPkPostId(utils.getNumberId());
                organization.setCreatedBy(person.getPersonnelName());
                row=organizationService.insert(organization);
                log.setLogTitle("增加模块");
            }
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"用户增加或者更新模块",e);
        }
        return map;
    }

    /**
     * 根据id查询的岗位信息
     *
     * @param pkPostId 岗位Id
     * @param request 请求
     * @return 岗位的信息
     */
    @GetMapping("selectById/{pkPostId}")
    @UserLoginToken
    public Map<String, Object> selectById(@PathVariable("pkPostId") Long pkPostId, HttpServletRequest request) {
        rowMap(request);
        try {
            OaOrganization oaOrganization = organizationService.selectByPostId(pkPostId);
            map.put("data",oaOrganization);
        } catch (Exception e) {
            addErrorLog(request,"根据id查询岗位",e);
        }
        return  map;
    }

    /**
     * 根据岗位ID查询岗位
     * @param pkPostId
     * @param request
     * @return
     */
    @GetMapping("findById/{pkPostId}")
    @UserLoginToken
    public Map<String, Object> findByPkPostId(@PathVariable("pkPostId") Long pkPostId, HttpServletRequest request) {
        rowMap(request);
        try {
            OaOrganizationVo oaOrganization = organizationService.selectByPkPostId(pkPostId);
            map.put("data",oaOrganization);
        } catch (Exception e) {
            addErrorLog(request,"根据id查询岗位",e);
        }
        return  map;
    }
    /**
     * 逻辑删除
     * @param pkPostId 部门ID
     * @param request  操作的
     * @return 操作的结果
     */
    @PutMapping("updateById/{pkPostId}")
    @UserLoginToken
    public Map<String, Object> updateById(@PathVariable("pkPostId") Long pkPostId, HttpServletRequest request) {
        rowMap(request);
        try {
            row = organizationService.updateById(pkPostId,person.getPersonnelName());
            log.setLogTitle("部门逻辑删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"部门逻辑删除模块块",e);
        }
        return map;
    }

    /**
     * 删除
     * @param pkPostId      岗位ID
     * @param request       操作的
     * @return 结果
     */
    @UserLoginToken
    @DeleteMapping("deletePost/{pkPostId}")
    public Map<String, Object> delete(@PathVariable("pkPostId") Long pkPostId, HttpServletRequest request) {
        rowMap(request);
        try {
            row= organizationService.delete(pkPostId);
            log.setLogTitle("岗位删除");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"岗位删除",e);
        }
        return map;
    }
    /**
     * 查询分页
     *
     * @param organization 公司信息
     * @param page      第几页
     * @param limit     返回的数据条数
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request   请求
     * @return 分页的数据和总数
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String, Object> findAll(OaOrganizationVo organization,
                                       Integer page, Integer limit,
                                       String startTime, String endTime,
                                       HttpServletRequest request) {
        try {
            List<OaOrganizationVo> all = organizationService.findAll(organization, page, limit, startTime, endTime);
            Long count = organizationService.rowCount(organization, startTime, endTime);
            return Tools.maps(all, count);
        } catch (Exception e) {
            addErrorLog(request,"岗位查询模块",e);
        }
        return null;
    }

    /**
     * 批量删除
     * @param ids 人员id的集合
     * @param request  请求
     * @return 删除的行数
     */
    @PostMapping("updateAll")
    @UserLoginToken
    public Map<String, Object> updateAll(@RequestParam(value = "ids[]",required = false) Long[] ids, HttpServletRequest request) {
        List<Long> idssi;
        if(ObjectUtils.isEmpty(ids)){

            return tools.rowMap(map,0,null);
        }else{
            idssi=Arrays.asList(ids);
        }
        rowMap(request);
        try {
            int updateAll = organizationService.updateAll(idssi,person.getPersonnelName());
            log.setLogTitle("岗位批量逻辑删除");
            log.setLogBody(JSON.toJSON(idssi).toString());
            log.setLogType("1");
            tools.rowMap(map, updateAll, log);
        } catch (Exception e) {
            addErrorLog(request,"岗位批量逻辑删除",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 人员id的集合
     * @param request 请求
     * @return 是否删除的
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
   public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpServletRequest request) {
        List<Long> idss;
        //判断转入的数据是否为空
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            idss= Arrays.asList(ids);
        }
        rowMap(request);
        try {
            int deleteAll = organizationService.deleteAll(idss);
            log.setLogTitle("岗位删除模块");
            log.setLogBody(JSON.toJSON(deleteAll).toString());
            log.setLogType("1");
            tools.rowMap(map, deleteAll, log);
        } catch (Exception e) {
            addErrorLog(request,"岗位删除模块",e);
        }
        return  map;
    }



    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        OaPersonnel personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(personnel.getPersonnelName());
        }
        tools.errorMap(log);
    }
    /**
     * 简化代码
     * @param request 请求
     */
    private void rowMap(HttpServletRequest request){

        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        person= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(person.getPersonnelName());
    }
}
